import {
  signIn,
  signOut,
  getMenuLists,
  getUserInfo
} from '@/api/login'

import router from '@/router';
import routes from '@/router/routes';
import Layout from '@/layout';
import Dashboard from '@/layout/dashboard'
// let Base64 = require('js-base64').Base64;
import _ from 'lodash';

const modules = import.meta.glob('@/pages/**/*.vue')
const layouts = import.meta.glob('@/layout/*.vue')

const user = {
  state: {
    userInfo: {},
    routeList: [], // 路由
    permissionList: [], // 按钮权限列表
    menuLists: [], // 只包含动态菜单，完整菜单需结合routes
  },
  mutations: {
    SET_USER_INFO(state, data) {
      state.userInfo = data
    },
    SET_ROUTE_LIST(state, data) {
      state.routeList = data
    },
    SET_PERMISSION_LIST(state, data) {
      state.permissionList = [...data, 'add']
    },
    SET_MENU_LIST(state, data) {
      state.menuLists = data
    }
  },
  actions: {
    Login({
      commit
    }, content) {
      return new Promise((resolve, reject) => {
        let passwordEncode = content.passWord.trim()
        signIn({...content, passWord: passwordEncode}).then(res => {
          if (res) {
            sessionStorage.setItem('token', `${res.token}`)
            resolve(res)
          }
        })
      })
    },
    GetUserInfo({
      commit,
      dispatch
    }, content) {
      return new Promise((resolve, reject) => {
        getUserInfo({clientId: '1'}).then(res => {
          if (res) {
            commit('SET_USER_INFO', {
              nickName: res.nickName,
              userName: res.userName,
            })
            // commit('SET_PERMISSION_LIST', res.permissions)
            let newMenus = res.menuList.map(o => {
              return {
                path: o.menuType == 1 ? `/${o.routeName}` : '',
                name: o.routeName,
                component: layouts[`../../layout/index.vue`],
                meta: {
                  title: o.menuName,
                  icon: o.menuIcon,
                  hidden: o.menuState,
                },
                children: o.menuType == 1 && o.children && o.children.length ? createTree(o.children) : createTree([o], true)
              }
            })
            function createTree(menus, flag){
              return menus.map((o, i) => {
                return {
                  path: o.routeName ? `${o.routeName}` : '',
                  name: flag ? `${o.routeName}_${i}` : o.routeName,
                  component: modules[`../../pages/${o.routePath}.vue`],
                  meta: {
                    title: o.menuName,
                    icon: o.menuIcon,
                    hidden: o.menuState,
                  },
                }
              })
            }
            commit('SET_MENU_LIST', newMenus)
            commit('SET_ROUTE_LIST', newMenus)
            const newRoutes = _.cloneDeep(newMenus)
            newRoutes.forEach(o => {
              if (o.children && o.children.length) o.redirect = `${o.path}/${o.children[0].path}`
              o.children.forEach(e => {
                if (e.children && e.children.length) {
                  o.children.push(...e.children)
                  delete e.children
                } else {
                  delete e.children
                }
              })
            })
            newRoutes.push({
              path: '*',
              redirect: '/404',
              hidden: true
            })
            resolve(newRoutes)
          } else {
            sessionStorage.clear()
          }
        }, ((err) => {
            console.log(err)
        }))
      })
    },
    LoginOut({
      commit
    }, content) {
      return new Promise((resolve, reject) => {
        signOut(content).then(res => {
          resolve(res)
        })
      })
    }
  }
}

export default user